<?php
/**
 * Created by xiaosong
 * E-mail:4155433@gmail.com
 * Date: 2019/7/4
 * Time: 14:52
 */

namespace app\common\exception;


use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\Log;
use think\Request;

class Handle extends \think\exception\Handle
{

    public function render(\Exception $e)
    {
        if (\request()->module() == 'api' && input('debug') !== 'debug'){

            $cache = cache('exception500');

            $error['msg'] = '小松自定义错误记录';
            $error['request']['param'] = \request()->param();
            $error['request']['header'] = \request()->header();

            $error['e'] = json_encode($e);

            $cache[] = $error;
            cache('exception500',$cache);

            Log::write($error,'xiaosong');

            //拦截api模块下的报错信息
            if ($e instanceof ModelNotFoundException){

                //找不到数据
                $result = [
                    'code' => 0,
                    'msg' =>  sprintf( '数据不存在(%s)',$e->getMessage()),
                    'time' => Request::instance()->server('REQUEST_TIME'),
                    'data' => null,
                ];
                return json($result,200);

            }elseif ($e instanceof Exception){

                $result = [
                    'code' => 0,
                    'msg' =>  $e->getMessage(),
                    'time' => Request::instance()->server('REQUEST_TIME'),
                    'data' => null,
                ];

                return json($result,200);
            }else{
                $result = [
                    'code' => 0,
                    'msg' =>  '服务器繁忙,请稍后重试!',
                    'time' => Request::instance()->server('REQUEST_TIME'),
                    'data' => null,
                    'e' => $e->getMessage()
                ];

                return json($result,200);
            }
        }

        return parent::render($e);
    }

}